<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd">添加物品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" @click="batchShow">上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" @click="batchHidden">下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" @click="batchDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-row class="mb8">
      <el-table
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="物品名称" align="center" prop="name" />
        <el-table-column label="状态" align="center" prop="onSale">
          <template #default="scope">
            <dict-tag :options="sale_status" :value="scope.row.onSale" />
          </template>
        </el-table-column>
        <el-table-column label="价格（渡币）" align="center" prop="price" />
        <el-table-column label="失效（小时）" align="center" prop="aging" />
        <el-table-column label="所属分类" align="center" prop="categoryName" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="170"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.gmtCreate) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <a
              href="javascript:;"
              style="color: #358de5; text-decoration: none; margin-right: 10px"
              @click="handleUpdate(scope.row, 1)"
              >查看</a
            >
            <a
              href="javascript:;"
              style="color: #358de5; text-decoration: none; margin-right: 10px"
              @click="handleUpdate(scope.row, 2)"
              >编辑</a
            >
            <a
            v-if="scope.row.onSale==0"
              href="javascript:;"
              style="color: #358de5; text-decoration: none; margin-right: 10px"
              @click="handleShow(scope.row)"
              >上架</a
            >
            <a
             v-if="scope.row.onSale==1"
              href="javascript:;"
              style="color: #fcb80b; text-decoration: none; margin-right: 10px"
              @click="handleHide(scope.row)"
              >下架</a
            >
            <a
              href="javascript:;"
              style="color: #f56c6c; text-decoration: none; margin-right: 10px"
              @click="handleDelete(scope.row)"
              >删除</a
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form
        @submit.native.prevent
        :model="form"
        :rules="rules"
        ref="userRef"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="物品名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="价格（渡币）" prop="price">
              <el-input
                type="number"
                v-model="form.price"
                placeholder="请输入"
                :min="1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="失效（小时）" prop="aging">
              <el-input
                type="number"
                v-model="form.aging"
                placeholder="请输入"
                :min="6"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择">
                <el-option
                  v-for="item in categorylist"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.onSale">
                <el-radio
                  v-for="dict in sale_status"
                  :key="dict.value"
                  :label="Number(dict.value)"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面图片" prop="imageUrl" required>
              <ImageUpload
                v-model="form.imageUrl"
                :materialType="1"
                :fileType="['png', 'jpg']"
              ></ImageUpload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="title !== '详情'">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
      
<script setup name="goods">
import {
  queryGoodsPage,
  addGoods,
  editGoods,
  goodsExport,
  onSaleGoods,
  offSaleGoods,
  deleteGoods,
} from "@/api/goods";
import {
  queryCategoryPage
} from "@/api/category";
const { proxy } = getCurrentInstance();
const { sale_status,  } = proxy.useDict(
  "sale_status"
);
const list = ref([]);
const categorylist= ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const data = reactive({
  form: {
    id: undefined,
    name: "",
    price: 1,
    aging: 6,
    onSale: 1,
    categoryId: "",
    imageUrl: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
  },
  rules: {
    aging: [
      { required: true, message: "失效不能为空", trigger: "blur" }],
    price:[
      { required: true, message: "价格不能为空", trigger: "blur" }
    ],
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    imageUrl: [{ required: true, message: "图片不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 选择条数  */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 查询用户列表 */
const getList = () => {
  loading.value = true;
  queryGoodsPage(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      loading.value = false;
      list.value = res.rows;
      total.value = Number(res.total);
    }
  );
};
const getCategory = () => {
  loading.value = true;
  queryCategoryPage({
    pageNum: 1,
    pageSize: 100,
  }).then(
    (res) => {
      loading.value = false;
      res.rows.map(item=>{
        categorylist.value.push({
            label:item.name,
            value:item.id,
        })
      })
    }
  );
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 1000,
  };
  handleQuery();
};

/** 批量显示 */
const batchShow = async () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning("请选择操作内容");
    return false;
  }
  let result = await onSaleGoods(ids.value.toString());
  if (result.code == 200) {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }
};

/** 批量隐藏 */
const batchHidden = async () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning("请选择操作内容");
    return false;
  }
  let result = await offSaleGoods(ids.value.toString());
  if (result.code == 200) {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }
};

/** 批量删除 */
const batchDelete = async () => {
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning("请选择操作内容");
    return false;
  }
  let result = await deleteGoods(ids.value.toString());
  if (result.code == 200) {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }
};

/** 导出按钮操作 */
const handleExport = async () => {
  proxy.$modal.loading("文件导出中，请稍候...");
  let result = await goodsExport();
  const blob = new Blob([result]);
  let link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "书籍列表_" + new Date().getTime() + ".xlsx";
  link.click();
  proxy.$modal.closeLoading();
};

/** 重置操作表单 */
const reset = () => {
  form.value = {
    id: undefined,
    name: "",
    aging: 6,
    onSale: 1,
    onSale: 1,
    categoryId: "",
    imageUrl: "",
	type:"TOMB_GIFT"
  };
  proxy.resetForm("userRef");
};

const handleAdd = () => {
  title.value = "新增";
  reset();
  open.value = true;
};
/** 取消按钮 */
const cancel = () => {
  open.value = false;
  changeScore.value = false;
  reset();
};

/** 下架按钮操作 */
const handleHide = (row) => {
  proxy.$modal
    .confirm("是否确认要下架" + row.name + "物品")
    .then(() => {
      return offSaleGoods(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("下架成功");
    })
    .catch(() => {});
};

/** 上架按钮操作 */
const handleShow = (row) => {
  proxy.$modal
    .confirm("是否确认上架该" + row.name + "物品")
    .then(() => {
      return onSaleGoods(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("上架成功");
    })
    .catch(() => {});
};

/** 删除按钮操作 */
const handleDelete = (row) => {
  proxy.$modal
    .confirm("是否确认要删除" + row.name + "物品")
    .then(() => {
      return deleteGoods(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
/** 修改按钮操作 */
const handleUpdate = (row, type) => {
  reset();
  title.value = type == 1 ? "详情" : "编辑";
  form.value = {
    ...row,
  };
  open.value = true;
};

/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
       if (form.value.id!==undefined) {
        editGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("编辑成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

getList();
getCategory()
</script>
      <style lang='scss' scoped>
</style>
      